<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
import api from '@renderer/api/print'
const timer = ref(null)
const printState = reactive({
  form: {
    pageNum: 1,
    pageSize: 999
  }
})
const options = {
  preview: false, // 是否在打印前预览，默认为 false
  width: '180px', // 纸张宽度，可以根据打印机调整
  margin: '0 0 0 0', // 边距
  copies: 1, // 打印份数
  printerName: '你的打印机名称', // 打印机名称，需与系统中的打印机名称一致
  timeOutPerLine: 400 // 每行打印的超时时间（毫秒）
}
const getTask = () => {
  console.log('ping')
  window.api
    .fetchData(
      api.treatTask(
        JSON.parse(
          JSON.stringify(printState.form)
        )
      )
    )
    .then((res) => {
      if (res.code === 200) {
        const overList = res.rows
          .filter((item) => item.internetUrl)
        overList.length && taskMatchPrint(overList[0])
      } else {
        message.error(res.msg)
      }
    }
    )
}

// 打印任务匹配打印机
const taskMatchPrint = async (over) => {
  let list = await window.api.getPrinterList()
  const printList = list.map((item) => {
    return {
      ...item,
      printerFid: item.options['device-uri']
    }
  })
  let findObj = printList.find((item) => item.printerFid === over.printerFid)
  print({ ...findObj, over })
}
// 对其进行打印
const print = async (obj) => {
  // 打印中
  let postData = JSON.parse(JSON.stringify(
    [{
      taskStatus: 'PRINTING',
      taskId: obj.over.taskId
    }]
  ))
  await window.api
    .fetchData(
      api.updateTasksStatus(postData)
    )


  window.api
    .printPage(obj.over.internetUrl, {
      silent: true, // 弹出系统打印对话框
      deviceName: obj.name,
      printBackground: true, // 打印背景
      color: !!obj.over.printColor, // 强制黑白打印
      landscape: obj.over.pageRange === '1' ? true : false, // 横向打印
      pageSize: obj.over.printPaper, // A3 纸张
      marginType: 'default' // 默认边距
    })
    .then(async (res) => {
      // 打印完成
      let postData = JSON.parse(JSON.stringify(
        [{
          taskStatus: 'PRINT_END',
          taskId: obj.over.taskId
        }]
      ))
      await window.api
        .fetchData(
          api.updateTasksStatus(postData)
        )
    }).catch(err => {
      // 打印失败
      let postData = JSON.parse(JSON.stringify(
        [{
          taskStatus: 'PRINT_FAILED',
          taskId: obj.over.taskId
        }]
      ))
      window.api
        .fetchData(
          api.updateTasksStatus(postData)
        )
        .then((res) => {
          if (res.code === 200) {

          } else {
            message.error(res.msg)
          }
        }
        )
    })
}
onMounted(() => {
  getTask()
  timer.value = setInterval(getTask, 20000)
})
onBeforeUnmount(() => {
  // 销毁前清除定时器
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>
